<template>
    <div>
        <div>
            <el-input type="text" style="width: 200px; margin-right: 5px;" placeholder="请输入id" v-model=inputid
                suffix-icon="el-icon-search"></el-input>
            <el-input type="text" style="width: 200px; margin-right: 5px;" placeholder="请输入用户名" v-model=inputusername
                suffix-icon="el-icon-search"></el-input>
            <el-input type="text" style="width: 200px; margin-right: 5px;" placeholder="请输入邮箱" v-model=inputemail
                suffix-icon="el-icon-search"></el-input>
            <el-input type="text" style="width: 200px; margin-right: 5px;" placeholder="请输入电话" v-model=inputtel
                suffix-icon="el-icon-search"></el-input>
            <el-button type="primary" @click="searchAll">搜索</el-button>
            <el-button type="info" @click="resetInput">重置</el-button>
        </div>
        <div style="margin-top: 10px;">
            <el-button type="primary" @click="AdddialogFormVisible = true">添加 <i
                    class="el-icon-circle-plus-outline"></i></el-button>
        </div>
        <el-table :data="tableData" :cell-style="{ textAlign: 'center' }">
            <el-table-column prop="id" label="ID" width="50" header-align="center"></el-table-column>
            <el-table-column prop="tx" label="tx" width="100" header-align="center">
                <template slot-scope="scope">
                    <img :src=scope.row.usertx alt="用户头像" width="50px" height="50px">
                </template> </el-table-column>
            <el-table-column prop="username" label="用户名" width="160" header-align="center"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="200" header-align="center"></el-table-column>
            <el-table-column prop="hobby" label="爱好" width="160" header-align="center"></el-table-column>
            <el-table-column prop="tel" label="电话" width="160" header-align="center"></el-table-column>
            <el-table-column prop="personality" label="性格" width="120" header-align="center"></el-table-column>
            <el-table-column label="操作" header-align="center">
                <template slot-scope="scope">
                    <el-button type="success" @click="EditById(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
                    <el-button type="danger" @click="deleteById(scope.row)">删除 <i
                            class="el-icon-delete"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :page-size="10" :total="totalUser">
        </el-pagination>

        <!-- 添加 AdddialogForm -->
        <el-dialog title="添加用户" :visible.sync="AdddialogFormVisible">
            <el-form :model="AdddialogForm" ref="AdddialogFormRef" :rules="AdddialogFormRules">
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                    <el-input v-model="AdddialogForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                    <el-input v-model="AdddialogForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="爱好" :label-width="formLabelWidth" prop="hobby">
                    <el-input v-model="AdddialogForm.hobby" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" :label-width="formLabelWidth" prop="tel">
                    <el-input v-model="AdddialogForm.tel" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性格" :label-width="formLabelWidth" prop="personality">
                    <el-input v-model="AdddialogForm.personality" autocomplete="off"></el-input>
                </el-form-item>
                <div style="display: flex;">
                    <div style="margin-left: 80px; margin-right: 30px;">头像:</div>
                    <el-upload class="avatar-uploader" ref="upload" action="" :on-preview="handlePreview"
                        :on-remove="handleRemove" :file-list="fileList" :auto-upload="false"
                        :before-upload="beforeAvatarUpload" :on-change="handleChange">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg文件，且不超过2M</div>
                    </el-upload>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="AdddialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="AdddialogFormSubmit">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 编辑 EditdialogForm -->
        <el-dialog title="修改用户" :visible.sync="EditdialogFormVisible">
            <el-form :model="EditdialogForm" ref="EditdialogFormRef" :rules="EditdialogFormRules">
                <el-form-item label="ID" :label-width="formLabelWidth">
                    <el-input v-model="EditdialogForm.id" autocomplete="off" readonly="true"></el-input>
                </el-form-item>
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                    <el-input v-model="EditdialogForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input v-model="EditdialogForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="爱好" :label-width="formLabelWidth">
                    <el-input v-model="EditdialogForm.hobby" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" :label-width="formLabelWidth" prop="tel">
                    <el-input v-model="EditdialogForm.tel" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性格" :label-width="formLabelWidth">
                    <el-input v-model="EditdialogForm.personality" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="EditdialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="EditdialogFormSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import axios from 'axios';
import request from '../utils/request';

export default {
    data() {
        return {
            tableData: [],
            imageUrl: '',
            inputid: "",
            inputusername: "",
            inputemail: "",
            inputtel: "",
            pageSize: 10,
            pageNum: 1,
            selectedFile: '',
            fileList: [],
            AdddialogFormVisible: false,
            EditdialogFormVisible: false,
            AdddialogForm: {},
            txUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            EditdialogForm: {
                id: '',
                username: '',
                email: '',
                hobby: '',
                tel: '',
                personality: ''
            },
            EditdialogFormRules: {//prop属性名必须与字段名相同,prop='username' == EditdialogForm.username
                username: [
                    { required: true, message: "用户名为必填项", trigger: 'blur' }
                ],
                tel: [
                    { required: true, message: "电话号码为必填项", trigger: 'blur' }
                ]
            },
            AdddialogFormRules: {//prop属性名必须与字段名相同,prop='username' == AdddialogForm.username
                username: [
                    { required: true, message: "用户名为必填项", trigger: 'blur' }
                ],
                email: [
                    { required: true, message: "邮箱为必填项", trigger: 'blur' },
                    { pattern:/^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/, required: true, message: "请正确输入邮箱格式", trigger: "blur" }
                ],
                tel: [
                    { required: true, message: "电话号码为必填项", trigger: 'blur' },
                    { pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/, required: true, message: "请正确输入号码格式", trigger: "blur" }
                ],
                hobby: [
                    { required: true, message: "爱好为必填项", trigger: 'blur' }
                ],
                personality: [
                    { required: true, message: "性格为必填项", trigger: 'blur' }
                ]
            },
            formLabelWidth: '120px'
        }
    },
    //界面初始化默认执行函数
    created() {
        this.PageDivide()
    },
    methods: {
        // handleFileChange(file) {
        //     this.selectedFile = file.raw; // 保存文件
        // },
        handleChange(file, fileList) {
            this.fileList = fileList;
            // console.log(this.fileList, "sb");
        },
        beforeAvatarUpload(file) {
            console.log("-------beforeAvatarUpload-------")
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt2M;
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        //实现查询
        async PageDivide() {
            const res = await request.get("user/findpage", {
                params: {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum
                }
            })
            console.log("-------------res--------------", res)
            if (res.total != 0) {
                this.tableData = res.data
                this.totalUser = res.total
            } else
                this.$message.error("分页查询错误!")
        },
        handleSizeChange(size) {
            this.pageSize = size
            this.PageDivide()
        },
        handleCurrentChange(num) {
            this.pageNum = num
            this.PageDivide()
        },
        //dialog 添加user
        AdddialogFormSubmit() {
            this.$refs.AdddialogFormRef.validate(async valid => {
                if (!valid) {
                    this.$message.error('请完善表单信息');
                    return;
                }
                const dialogRes = await request.post("user/adduser", this.AdddialogForm)
                if (dialogRes == 1) {
                    this.AdddialogFormVisible = false
                    this.$message.success("用户添加成功!")
                    this.upload()
                    this.$refs.AdddialogFormRef.resetFields()
                    this.PageDivide()
                } else {
                    this.$message.error("添加错误")
                }
            })
        },
        async upload() {
            let formData = new FormData()
            formData.append("username", this.AdddialogForm.username)
            formData.append("file", this.fileList[0].raw)
            // 调试：打印 formData 的实际内容
            for (let [key, value] of formData.entries()) {
                console.log(`${key}:`, value);
            }
            const res = await request.post("user/uploadTx", formData)
        },
        //单个删除按钮
        async deleteById(row) {
            const id = row.id
            const res = await request.delete(`user/${id}`)
            if (res == 1) {
                this.$message.success("用户名为 " + row.username + " 的用户已被删除!")
                this.PageDivide()
            }
            else
                this.$message.error("删除错误!")
        },
        //使编辑dialog拥有默认值
        EditById(row) {
            this.EditdialogFormVisible = true
            this.EditdialogForm.id = row.id
            this.EditdialogForm.username = row.username
            this.EditdialogForm.email = row.email
            this.EditdialogForm.hobby = row.hobby
            this.EditdialogForm.personality = row.personality
            this.EditdialogForm.tel = row.tel
        },
        //编辑dialog 提交
        EditdialogFormSubmit() {
            this.$refs.EditdialogFormRef.validate(async valid => {
                if (!valid) {
                    this.$message.error("编辑错误!!")
                    return;
                }
                const dialogRes = await request.post("user/update", this.EditdialogForm)
                if (dialogRes == 1) {
                    this.EditdialogFormVisible = false
                    this.$message.success("修改成功!")
                    this.PageDivide()
                } else {
                    this.$message.error("添加错误")
                }
            })
        },
        //多条件查询
        async searchAll() {
            const searid = this.inputid
            const searusername = this.inputusername
            const searemail = this.inputemail
            const seartel = this.inputtel
            const resuser = await request.get("user/findmul", {
                params: {
                    id: searid,
                    username: searusername,
                    email: searemail,
                    tel: seartel
                }
            })
            if (resuser.length != null) {
                this.tableData = resuser//后端定义返回的格式要是List<user>
                this.totalUser = resuser.length
            } else
                this.$message.error("查找错误!")
        },
        //重置按钮事件
        resetInput() {
            this.inputid = '',
                this.inputemail = '',
                this.inputtel = '',
                this.inputusername = '',
                this.PageDivide()
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
       
    }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>